package com.geek.javase.ch17.work.bswork;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/*
 *@Date 2025/11/4
 *@Author wangpeng
 *@Description
 *  * 浏览器充当客户端，访问：http://192.168.21.7:8888
 * 服务器响应HTML内容 PrintStream
 * HTTP/1.1 200 OK
 * Content-Type: text/html; charset=utf-8
 * 欢迎 IP 上线！
 */
public class BS {
    public static void main(String[] args) {
        //创建线程池
        ThreadPool pool = new ThreadPool(10, 30);
        ServerSocket ss = null;
        try{
            //创建服务器套接字
            ss = new ServerSocket(8899);
            System.out.println("BS服务器已启动！");
            while(true){
                //无限接收客户端
                Socket s = ss.accept();
                pool.execute(()->{
                    try{
                        PrintStream ps = new PrintStream(s.getOutputStream());
                        //响应
                        ps.println("HTTP/1.1 200 OK");
                        ps.println("Content-Type: text/html; charset=utf-8");
                        //ps.println("Content-Type: text/json; charset=utf-8");
                        //响应一个换行符
                        ps.println();
                        //响应页面内容
                        ps.println("<html><h1 style='color:black'>欢迎"+s.getRemoteSocketAddress()+"上线</h1></html>");
                        //ps.println("{IP:"+s.getRemoteSocketAddress()+"}");
                        //刷新
                        ps.flush();
                        //关闭流
                        ps.close();

                    }catch(Exception e){
                        e.printStackTrace();
                    }
                });
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
